package com.vftour.stu.base.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ThreadLockDemo
 *
 * @version 1.0
 * @author: 东东 | d@tke.store
 * @date :  2022/3/2 9:57 下午
 */
public class ThreadLockDemo {
    static Object objectLock = new Object();

    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void lockAwaitSignal(){

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + ",进来了");
                try {
                    condition.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ",被唤醒");
            }finally {
                lock.unlock();
            }
        },"Wait").start();

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + ",通知");
            }finally {
                lock.unlock();
            }
        },"Notify").start();
    }

    public static void objectWaitNotify(){
        new Thread(() -> {
            synchronized (objectLock) {
                System.out.println(Thread.currentThread().getName() + ",进来了");
                try {
                    objectLock.wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ",被唤醒");
            }
        },"Wait").start();

        new Thread(() -> {
            synchronized (objectLock) {
                objectLock.notify();
                System.out.println(Thread.currentThread().getName() + ",通知");
            }
        },"Notify").start();
    }

    public static void lockSupportLock(){
        Thread wait = new Thread(() -> {
            synchronized (objectLock) {
                System.out.println(Thread.currentThread().getName() + ",进来了");
                LockSupport.park();
                System.out.println(Thread.currentThread().getName() + ",被唤醒");
            }
        },"Wait");
        wait.start();

        new Thread(() -> {
            LockSupport.unpark(wait);
            System.out.println(Thread.currentThread().getName() + ",通知");
        },"Notify").start();
    }

    public static void main(String[] args) {
//        objectWaitNotify();
//        lockAwaitSignal();
        lockSupportLock();
    }
}
